import {
  borrowPageApi,
  addBorrowApi,
  editBorrowApi,
  delBorrowApi
} from '@/api/workflow/borrow'
import { Ref } from 'vue'
import { ProTableInst } from '@/components/pro-table/type'
import { PageRequest } from '@/api/types'
import { BorrowModel } from '@/api/model/borrow-model'
import { userInfo } from '~/types/user'
import { userInfoModel } from '@/api/model/userModel'
import dayjs from 'dayjs'

type Props = {
  handleType: Ref<'add' | 'edit' | 'check'>
  handleTag: Ref<string>
  borrowModalShow: Ref<boolean>
  borrowForm: Ref<Partial<BorrowModel>>
  proTableInst: Ref<ProTableInst | null>
  userInfo: Ref<userInfo<userInfoModel>>
  orgOptions: Ref<any>
}

export const useBorrowApi = ({
  handleType,
  handleTag,
  borrowModalShow,
  borrowForm,
  proTableInst,
  userInfo,
  orgOptions
}: Props) => {
  const confirmLoading = ref(false)

  // 获取借用列表
  const fetchBorrowPage = async (
    pageRequest: PageRequest,
    queryParams: BorrowModel
  ) => {
    const res = await borrowPageApi({
      ...queryParams,
      orgId: userInfo.value.orgId,
      pageRequest
    })

    if (res.code === '0000') {
      return {
        data: res.data?.content,
        total: res.data?.total
      }
    }
  }

  // 新增or修改借用
  const fetchAddOrEditBorrow = async () => {
    confirmLoading.value = true
    const fetch = handleType.value === 'add' ? addBorrowApi : editBorrowApi
    const data =
      handleType.value === 'add'
        ? {
            ...borrowForm.value,
            receivePerson: userInfo.value.userName,
            receivePersonId: userInfo.value.userId,
            receiveBranch: userInfo.value.orgName,
            receiveBranchId: userInfo.value.orgId,
            borrowOutBranch: useDictDisplay(
              orgOptions.value,
              borrowForm.value.borrowOutBranchId
            ),
            receiveDate: dayjs().format('YYYY-MM-DD')
          }
        : {
            ...borrowForm.value
          }
    if (data.__displayValue__) delete data.__displayValue__
    const res = await fetch(data)
    console.log('data', data, userInfo.value.userName, userInfo.value)
    if (res.code === '0000') {
      useMsg('success', handleTag.value + '成功')
      proTableInst.value?.reload()
      borrowModalShow.value = false
    }

    confirmLoading.value = false
  }

  // 删除借用
  const fetchDelBorrow = async (id) => {
    const res = await delBorrowApi({ id })
    if (res.code === '0000') {
      useMsg('success', '删除成功')
      proTableInst.value?.reload()
    }
  }

  return {
    fetchBorrowPage,
    fetchAddOrEditBorrow,
    fetchDelBorrow,
    confirmLoading
  }
}
